package com.kaili.controller.web.v1;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.client.service.ILoginUserInfoService;
import com.kaili.common.exception.BaseExcept;
import com.kaili.common.util.BarcodeUtil;
import com.kaili.common.util.FreemarkUtils;
import com.kaili.common.util.LoginDetailUtils;
import com.kaili.db.service.IHsBasicSeqService;
import com.kaili.db.service.IHsEwbsStowageService;
import com.kaili.db.service.IHsOptEwbAppointService;
import com.kaili.db.service.IHsOptEwbService;
import com.kaili.except.ResponseStatus;
import com.kaili.feign.UserFeignClient;
import com.kaili.pojo.dto.ewb.EwbAddDTO;
import com.kaili.pojo.dto.ewb.EwbQueryDTO;
import com.kaili.pojo.vo.EwbQueryVO;
import com.kaili.pojo.vo.EwbSummaryVO;
import com.kaili.version.ApiVersion;
import freemarker.template.Configuration;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Pattern;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ApiVersion(1)
@RequestMapping("/{api_version}")
@RestController
@Validated
@Api(tags = "托运开单服务", description = "托运开单相关API")
public class EwbController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MessageSource messageSource;

    @Autowired
    IHsOptEwbAppointService ewbAppointService;
    @Autowired
    IHsBasicSeqService seqService;

    @Autowired
    ILoginUserInfoService loginUserInfoService;
    @Autowired
    IHsOptEwbService ewbService;

    @Autowired
    Configuration configuration;

    @Autowired
    IHsEwbsStowageService stowageService;

    @Autowired
    private UserFeignClient userFeignClient;

    @PostMapping(value = "/ewbs")
    @ApiOperation(value = "新增运单", notes = "新增托运开单")
    public ResponseStatus doAddEwb(@Validated @RequestBody EwbAddDTO addBean) {
        // 1.校验
        ResponseStatus result = com.kaili.controller.common.v1.EwbController.check(ewbService,stowageService,addBean);
        if(200 != result.getCode()){
            return result;
        }

        // 2.保存或修改
        int ret = ewbService.doAddEwb(addBean);
        if (ret != 0) {
            return ResponseStatus.EWB_ADD_ERR;
        }
        return ResponseStatus.RESPONSE_OK;
    }

    @PutMapping(value = "/ewbs/{ewbNo}")
    @ApiOperation(value = "修改运单", notes = "修改托运开单")
    public ResponseStatus doUpdateEwb(@Validated @RequestBody EwbAddDTO addBean) {
        // 1.校验
        ResponseStatus result = com.kaili.controller.common.v1.EwbController.check(ewbService,stowageService,addBean);
        if(200 != result.getCode()){
            return result;
        }

        // 2.保存或修改
        int ret = ewbService.doAddEwb(addBean);
        if (ret != 0) {
            return ResponseStatus.EWB_ADD_ERR;
        }
        return ResponseStatus.RESPONSE_OK;
    }

    @ApiOperation(value = "删除托运单")
    @DeleteMapping("/ewbs/{ewbNo}")
    public ResponseStatus deleteEwbNo(
            @Pattern(regexp = "^[A-Za-z0-9]{1,30}$", message = "运单号应为[A-Za-z0-9]组成的1-30位字符")
            @PathVariable("ewbNo") @ApiParam(value = "运单号", defaultValue = "0000011111") String ewbNo) {
        if(!ewbService.isEwbNoRepeat(ewbNo)){
            return ResponseStatus.EWB_NOT_EXISTS;
        }

        if(stowageService.isStowage(ewbNo)){
            return ResponseStatus.EWB_NOT_DELETE;
        }

        ewbService.deleteEwbNo(ewbNo);
        return ResponseStatus.RESPONSE_OK;
    }


    @ApiOperation(value ="判断运单是否重复")
    @GetMapping("/ewbs/{ewbNo}/repeat")
    public ResponseStatus isEwbNoRepeat(
            @Pattern(regexp = "^[A-Za-z0-9]{1,30}$", message = "运单号应为[A-Za-z0-9]组成的1-30位字符")
            @PathVariable("ewbNo") @ApiParam(value = "运单号", defaultValue = "0000011111") String ewbNo) {
        if(ewbService.isEwbNoRepeat(ewbNo.trim())){
            return ResponseStatus.EWB_ADD_DUPLICATE;
        }

        return ResponseStatus.RESPONSE_OK;
    }

    @GetMapping("/ewbs")
    @ApiOperation(value = "分页查询开单数据列表")
    public Page<EwbQueryVO> queryEwbList(@Validated @ModelAttribute EwbQueryDTO req) throws BaseExcept {
        if(req.getCur()!=null&&req.getPageSize()!=null){
            Map<Object,Object> param=new HashMap<>();
            param.putAll(new BeanMap(req));
            Integer siteId = LoginDetailUtils.getSiteId();
            if (siteId != null && siteId != 1){
                param.put("siteId", siteId);
            }
            Page<EwbQueryVO> pager = new Page<EwbQueryVO>(req.getCur(), req.getPageSize());
            pager = ewbService.queryEwbList(pager,param);
            return pager;
        }
        throw new BaseExcept(ResponseStatus.EWB_QUERY_ERR);
    }

    @GetMapping("/ewbs/summary")
    @ApiOperation(value = "获取运单汇总数据")
    public EwbSummaryVO queryEwbSummary(@Validated @ModelAttribute EwbQueryDTO req) throws BaseExcept {
        Map<Object,Object> param=new HashMap<>();
        param.putAll(new BeanMap(req));

        Integer siteId = LoginDetailUtils.getSiteId();
        if (siteId != null && siteId != 1){
            param.put("siteId", siteId);
        }
        return ewbService.queryEwbSummary(param);
    }

    @GetMapping("/ewbs/{ewbsNo}/totalPiece")
    @ApiOperation(value = "根据运单号查询运单总件数")
    public Integer getInfoByEwbNo(@Pattern(regexp = "^[A-Za-z0-9]{1,30}$",message = "运单号应为[A-Za-z0-9]组成的1-30位字符") @PathVariable("ewbsNo") String ewbNo) throws BaseExcept {
        Map<Object,Object> map=new HashMap<>();
        map.put("siteId", loginUserInfoService.getLoginSiteId());
        map.put("ewbNo", ewbNo);
        //判断网点是否存在
        Integer count = ewbService.getInfoByEwbNoCount(map);
        if (count == null) {
            return -1; //单号不存在
        }
        //判断登陆网点作为目的网点进行查询看是否存在
        Integer result = ewbService.getInfoByEwbNo(map);

        if (result == null) {
            return 0; //单号存在 但是当前登录网点无权操作
        }
        return result;
    }

    @GetMapping("/ewbs/html")
    @ApiOperation(value = "获取运单打印html数据")
    public String queryEwbPrint(@RequestParam("ewbNos") @ApiParam(value="运单号逗号连接字符串",defaultValue = "0000011111") String ewbNos) throws BaseExcept {
        if(StringUtils.isEmpty(ewbNos)){
            throw new BaseExcept(ResponseStatus.PRINT_NULL);
        }

        String logo = userFeignClient.getCompanyLogo(Long.parseLong(LoginDetailUtils.getCompanyCode()));
        JSONObject json= JSON.parseObject(logo);
        List<String> ewbNoList = Arrays.asList(ewbNos.split(","));
        Map parm = new HashMap();
        parm.put("ewbNoList",ewbNoList);
        List<EwbQueryVO> list = ewbService.queryEwbList(parm);
        for(EwbQueryVO vo : list){
            vo.setBarcodeMsg(BarcodeUtil.generateBase64(vo.getEwbNo()));
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("list",list);
        map.put("companyName", LoginDetailUtils.getCompanyName());
        if(StringUtils.isEmpty(String.valueOf(json.get("data")))){
            map.put("pictureUrl","../api/static/logo.png");
        }else {
            map.put("pictureUrl", json.get("data"));
        }
        return FreemarkUtils.getPrintTemplate(configuration,"ewb", map);
    }
}